package com.toKnow.controller;



import com.toKnow.model.entity.*;
import com.toKnow.model.vo.ArticlePubOV;
import com.toKnow.model.vo.BasicVo;
import com.toKnow.model.vo.CommonResult;
import com.toKnow.model.vo.ThreeReturn;
import com.toKnow.service.ArticlePubService;
import com.toKnow.service.ArticleService;
import com.toKnow.service.TypeTagPubService;
import com.toKnow.utils.JwtUserSessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/api")
public class ArticlePubController {

    @Autowired
    private  ArticlePubService   articlePubService;
    @Autowired
    private TypeTagPubService typeTagPubService;

    @Autowired
    private ArticleService articleService;

    public void setArticlePubService(ArticlePubService articlePubService) {
        this.articlePubService = articlePubService;
    }

    public void setTypeTagPubService(TypeTagPubService typeTagPubService) {
        this.typeTagPubService = typeTagPubService;
    }

    private Integer getUid(HttpSession session) {
        String userToken = (String) session.getAttribute("userToken");
        String user_id_string = JwtUserSessionUtil.getInfo(userToken,"id");
        if(user_id_string == null) {
            return -1;
        } else {
            return Integer.valueOf(user_id_string);
        }
    }

    @RequestMapping(value = "/article/content/submit",method = RequestMethod.POST)
    @ResponseBody
    public ArticlePubOV addArticle(HttpServletRequest request, String title, Integer date,
                                   String type, String tag,
                                   Integer original, String content, MultipartFile file,
                                   MultipartFile cover,String digest){
        ArticlePubOV articlePubOV = new ArticlePubOV();

        HttpSession session = request.getSession();

        Integer user_id = getUid(session);
        if(user_id == -1) {
            articlePubOV.setMessage("请先登录");
            return articlePubOV;
        }

        //处理digest
        if(digest == null || digest.length()==0){

            if(content.length() <=100){
                digest = content;
            }else {
                digest = content.substring(0,99);
            }
        }


        //处理file
        String filePath = null;
        if(file != null ) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = file.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("") + "static\\article_attachment" + File.separator + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                file.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }

            filePath = File.separator
                + "static"
                + File.separator
                + "article_attachment"
                + File.separator
                + fileName;

        }else {
            filePath =null;
        }


        //处理cover
        String coverPath = null;
        if(cover != null ) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(cover.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                 suffix = cover.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "article_cover"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                cover.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }

            coverPath = File.separator +
                "static"
                + File.separator
                + "article_cover"
                + File.separator
                + fileName;

        }else {
            coverPath =null;
        }


        //将tag type 的 name 改为id

        List<String> type1 =null;
        List<String> tag1 = null;

        if(tag!=null ){
            tag1 = Arrays.asList(tag.split(","));
        }
        if(type!=null){
            type1 = Arrays.asList(type.split(","));
        }

        List<Integer> tags = typeTagPubService.convertTagNameToId(tag1);
        List<Integer> types = typeTagPubService.convertTypeNameToId(type1);

        //插入文章表
        ArticlePub articlePub = new ArticlePub();

        Timestamp t1 = new Timestamp(System.currentTimeMillis());

        articlePub.setPublish_date(t1);
        articlePub.setAuthor_id(user_id);
        articlePub.setTitle(title);
        if(original==1){
            articlePub.setIs_origin(1);
        }else {
            articlePub.setIs_origin(0);
        }
        articlePub.setContent(content);
        articlePub.setAttachment(filePath);
        articlePub.setCover(coverPath);
        articlePub.setDigest(digest);
        articlePub.setTagIds(tags);
        articlePub.setTypeIds(types);

        //修改用户的发表文章数
        UserInfoPub userInfoPub = new UserInfoPub();
        userInfoPub.setId(user_id);

        Integer article_id = articlePubService.addArticle(articlePub,userInfoPub);

        articlePubOV.setArticle_id(String.valueOf(article_id));
        articlePubOV.setSuccess(true);
        articlePubOV.setMessage("success");
        return articlePubOV;
    }

    @RequestMapping(value = "/article/content/store",method = RequestMethod.POST)
    @ResponseBody
    public ArticlePubOV storeArticle(HttpServletRequest request, String title, Integer date,
                                   String type, String tag,
                                   Integer original, String content, MultipartFile file,
                                   MultipartFile cover,String digest){
        ArticlePubOV articlePubOV = new ArticlePubOV();

        HttpSession session = request.getSession();

        Integer user_id = getUid(session);
        if(user_id == -1) {
            articlePubOV.setMessage("请先登录");
            return articlePubOV;
        }

        //处理file
        String filePath = null;
        if(file != null ) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = file.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "article_draft_attachment"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                file.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }

            filePath = File.separator
                + "static"
                + File.separator
                + "article_draft_attachment"
                + File.separator
                + fileName;

        }else {
            filePath =null;
        }

        //处理cover
        String coverPath = null;
        if(cover != null ) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(cover.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = cover.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "article_draft_cover"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                cover.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }


            coverPath = File.separator +
                "static"
                + File.separator
                + "article_draft_cover"
                + File.separator
                + fileName;

        }else {
            coverPath =null;
        }

        //将tag type 的 name 改为id

        List<String> type1 =null;
        List<String> tag1 = null;

        if(tag!=null ){
            tag1 = Arrays.asList(tag.split(","));
        }
        if(type!=null){
            type1 = Arrays.asList(type.split(","));
        }

        List<Integer> tags = typeTagPubService.convertTagNameToId(tag1);
        List<Integer> types = typeTagPubService.convertTypeNameToId(type1);

        //插入文章表
        ArticlePub articlePub = new ArticlePub();

        Timestamp t1 = new Timestamp(System.currentTimeMillis());

        articlePub.setPublish_date(t1);
        articlePub.setAuthor_id(user_id);
        articlePub.setTitle(title);
        if(original==1){
            articlePub.setIs_origin(1);
        }else {
            articlePub.setIs_origin(0);
        }
        articlePub.setContent(content);
        articlePub.setAttachment(filePath);
        articlePub.setCover(coverPath);
        articlePub.setDigest(digest);
        articlePub.setTagIds(tags);
        articlePub.setTypeIds(types);

        //修改用户的发表文章数
        UserInfoPub userInfoPub = new UserInfoPub();
        userInfoPub.setId(user_id);

        Integer article_id = articlePubService.storeArticle(articlePub,userInfoPub);

        articlePubOV.setArticle_id(String.valueOf(article_id));
        articlePubOV.setSuccess(true);
        articlePubOV.setMessage("success");
        return articlePubOV;

    }

    @RequestMapping(value = "/article/content/draft/update",method = RequestMethod.POST)
    @ResponseBody
    public ArticlePubOV updateArticleDraft(HttpServletRequest request,
        HttpSession session, Integer draft_id, String title, Integer date,
                                     String type, String tag,
                                     Integer original, String content, MultipartFile file,
                                     MultipartFile cover,String digest){

        ArticlePubOV articlePubOV = new ArticlePubOV();

        Integer user_id = getUid(session);

        if(user_id == -1) {
            articlePubOV.setMessage("请先登录");
            return articlePubOV;
        }

        if(draft_id == null) {
            articlePubOV.setSuccess(false);
            articlePubOV.setMessage("未携带草稿编号");
            return articlePubOV;
        }

        Article draftArticle = articleService.selectArticleDraftById(user_id, draft_id);

        if(draftArticle == null) {
            articlePubOV.setSuccess(false);
            articlePubOV.setMessage("未找到草稿");
            return articlePubOV;
        }

        //处理file
        String filePath = null;
        if(file != null ) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = file.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "article_draft_attachment"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                file.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }

            filePath = File.separator
                + "static"
                + File.separator
                + "article_draft_attachment"
                + File.separator
                + fileName;

        }else {
            filePath =null;
        }

        //处理cover
        String draftCoverPathPart = draftArticle.getCover();
        if(draftCoverPathPart != null) {
            String draftCoverPath = request.getServletContext().getRealPath("")
                + draftCoverPathPart;
            File delFile = new File(draftCoverPath);
            delFile.delete();
        }

        String coverPath = null;
        if(cover != null ) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(cover.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = cover.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "article_draft_cover"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                cover.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }


            coverPath = File.separator +
                "static"
                + File.separator
                + "article_draft_cover"
                + File.separator
                + fileName;

        }else {
            coverPath =null;
        }

        //将tag type 的 name 改为id

        List<String> type1 =null;
        List<String> tag1 = null;

        if(tag!=null ){
            tag1 = Arrays.asList(tag.split(","));
        }
        if(type!=null){
            type1 = Arrays.asList(type.split(","));
        }

        List<Integer> tags = typeTagPubService.convertTagNameToId(tag1);
        List<Integer> types = typeTagPubService.convertTypeNameToId(type1);

        //插入文章表
        ArticlePub articlePub = new ArticlePub();

        Timestamp t1 = new Timestamp(System.currentTimeMillis());

        articlePub.setPublish_date(t1);
        articlePub.setAuthor_id(user_id);
        articlePub.setTitle(title);
        if(original==1){
            articlePub.setIs_origin(1);
        }else {
            articlePub.setIs_origin(0);
        }
        articlePub.setContent(content);
        articlePub.setAttachment(filePath);
        articlePub.setCover(coverPath);
        articlePub.setDigest(digest);
        articlePub.setTagIds(tags);
        articlePub.setTypeIds(types);

        //修改用户的发表文章数
        UserInfoPub userInfoPub = new UserInfoPub();
        userInfoPub.setId(user_id);

        Integer article_id = articlePubService.updateDraft(draft_id, articlePub,userInfoPub);

        articlePubOV.setArticle_id(String.valueOf(article_id));
        articlePubOV.setSuccess(true);
        articlePubOV.setMessage("success");
        return articlePubOV;

    }

    // 添加专栏内容
/*    @RequestMapping(value = "/column/content/add",method = RequestMethod.POST)
    @ResponseBody
    public ThreeReturn moveArticleToColumn(HttpServletRequest request,Integer column_id,Integer article_id){

        int flag = 0;  // 当token检查不通过时，flag为1

        //以下是检查token  组合项目时 解除注释

        String userToken = (String) request.getSession().getAttribute("userToken");
        Boolean verifyToken = JwtUserSessionUtil.verify(userToken);
        if(verifyToken==false){
            flag=1;
        }

        ThreeReturn threeReturn = new ThreeReturn();

        if( flag ==0 ){
            int i = articlePubService.moveArticleToColumn(article_id,column_id);

            if(i==1){
                threeReturn.setSuccess(true);
                threeReturn.setMessage("success");
            }else {
                threeReturn.setSuccess(false);
                threeReturn.setMessage("false");
            }
        }else {
            threeReturn.setSuccess(false);
            threeReturn.setMessage("false token");
        }


        return  threeReturn;

    }*/

    // 回复评论
/*    @RequestMapping(value = "/article/content/comment/reply/submit",method = RequestMethod.POST)
    @ResponseBody
    public ThreeReturn answerArticleComment(Integer user_id,Integer date,String content,Integer comment_id){

        //若前端不提供 user_id 则 从token 中获取
        //String userToken = (String) request.getSession().getAttribute("userToken");
        //Integer user_id = Integer.valueOf( JwtUserSessionUtil.getInfo(userToken,"id") );

        ArticleCommentAnswerPub articleCommentAnswerPub = new ArticleCommentAnswerPub();
        articleCommentAnswerPub.setUser_id(user_id);
        articleCommentAnswerPub.setArticle_comment_id(comment_id);
        articleCommentAnswerPub.setContent(content);

        Timestamp t1 =new Timestamp( System.currentTimeMillis() );

        articleCommentAnswerPub.setAnswer_date(t1);


         int i = articlePubService.answerArticleComment(articleCommentAnswerPub);

        ThreeReturn threeReturn = new ThreeReturn();
        if(i==1){
            threeReturn.setSuccess(true);
            threeReturn.setMessage("success");
        }else {
            threeReturn.setSuccess(false);
            threeReturn.setMessage("false");
        }
        return  threeReturn;

    }*/

    // 评论
    // transactional right
    @RequestMapping(value = "/article/content/comment/submit",method = RequestMethod.POST)
    @ResponseBody
    public BasicVo commentArticle(HttpSession session, Integer date, String content, Integer article_id)  {

        BasicVo cm = new BasicVo(false, "", null);

        Integer user_id = getUid(session);
        if(user_id == -1) {
            cm.setMessage("请先登录");
            return cm;
        }

        Integer author_id  = articlePubService.findAuthor(article_id);

        ArticleCommentPub articleCommentPub = new ArticleCommentPub();
        articleCommentPub.setArticle_id(article_id);
        articleCommentPub.setContent(content);
        articleCommentPub.setUser_id(user_id);

        Timestamp ts=  new Timestamp( System.currentTimeMillis() );
        articleCommentPub.setComment_date(ts);


        UserInfoPub userInfoPub = new UserInfoPub();
        userInfoPub.setId(author_id);

        int i = articlePubService.commentArticle(articleCommentPub,article_id,userInfoPub);

        if(i==1){
            cm.setSuccess(true);
            cm.setMessage("success");
        }else {
            cm.setSuccess(false);
            cm.setMessage("false");
        }
        return  cm;
    }

    @RequestMapping(value = "/article/content/like",method = RequestMethod.POST)
    @ResponseBody
    public BasicVo likeArticle(HttpSession session, Integer article_id){

        BasicVo cm = new BasicVo(false, "", null);

        //若前端不提供 user_id 则 从token 中获取
        Integer user_id = getUid(session);
        if(user_id == -1) {
            cm.setSuccess(false);
            cm.setMessage("请先登录");
            return cm;
        }

        Integer author_id = articlePubService.findAuthor(article_id);

        ArticleLikePub articleLikePub = new ArticleLikePub();
        articleLikePub.setArticle_id(article_id);
        articleLikePub.setUser_id(user_id);
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        articleLikePub.setLike_date(ts);

        int i = articlePubService.likeArticle(articleLikePub,article_id,author_id);

        if(i==1){
            cm.setSuccess(true);
            cm.setMessage("success like");
        }else if(i==2){
            cm.setSuccess(true);
            cm.setMessage("success unlike");
        }else {
            cm.setSuccess(false);
            cm.setMessage("false");
        }

        return  cm;

    }


    // 点赞评论
/*    @RequestMapping(value = "/article/content/comment/like",method = RequestMethod.POST)
    @ResponseBody
    public ThreeReturn likeComment(Integer comment_id,Integer user_id){

        //若前端不提供 user_id 则 从token 中获取
        //String userToken = (String) request.getSession().getAttribute("userToken");
        //Integer user_id = Integer.valueOf( JwtUserSessionUtil.getInfo(userToken,"id") );

        ArticleCommentLikePub articleCommentLikePub = new ArticleCommentLikePub();
        articleCommentLikePub.setUser_id(user_id);
        articleCommentLikePub.setComment_article_id(comment_id);

        int i = articlePubService.likeComment(articleCommentLikePub,comment_id);

        ThreeReturn threeReturn = new ThreeReturn();
        if(i==1){
            threeReturn.setSuccess(true);
            threeReturn.setMessage("success like");
        }else if(i==2) {
            threeReturn.setSuccess(true);
            threeReturn.setMessage("success unlike");
        } else {
            threeReturn.setSuccess(false);
            threeReturn.setMessage("false");
        }
        return  threeReturn;

    }*/

    // 点赞评论回复
/*    @RequestMapping(value = "/article/content/comment/reply/like",method = RequestMethod.POST)
    @ResponseBody
    public ThreeReturn likeAnswer(Integer reply_id,Integer user_id){

        //若前端不提供 user_id 则 从token 中获取
        //String userToken = (String) request.getSession().getAttribute("userToken");
        //Integer user_id = Integer.valueOf( JwtUserSessionUtil.getInfo(userToken,"id") );

        ArticleAnswerLikePub articleAnswerLikePub = new ArticleAnswerLikePub();
        articleAnswerLikePub.setUser_id(user_id);
        articleAnswerLikePub.setAnswer_article_id(reply_id);

        int i = articlePubService.likeAnswer(articleAnswerLikePub,reply_id);

        ThreeReturn threeReturn = new ThreeReturn();
        if(i==1){
            threeReturn.setSuccess(true);
            threeReturn.setMessage("success like");
        }else if(i==2){
            threeReturn.setSuccess(true);
            threeReturn.setMessage("success unlike");
        }else{
            threeReturn.setSuccess(false);
            threeReturn.setMessage("false");
        }

        return  threeReturn;

    }*/
}
